<template>
  <div class="over-hiden" @mousewheel="mousewheel" @mousedown="mousedown">
    <canvas class="rel" :height="height" :width="width" ref="canvas"></canvas>
  </div>
</template>
<script lang="ts" setup>
import { onMounted, getCurrentInstance, inject, Ref, watchEffect } from 'vue'
import { mul, add, between, secToTime } from '@/lib/util'
import { getTimeInterval } from '@/console/timeline'
function drawTimeline(
  canvas: HTMLCanvasElement | unknown,
  timeInterval = 1,
  pxInterval = 200
) {
  if (canvas instanceof HTMLCanvasElement) {
    const cxt = canvas.getContext('2d')
    if (cxt) {
      const canvasWidth = canvas.clientWidth
      const canvasHeight = canvas.clientHeight

      cxt.clearRect(0, 0, canvasWidth, canvasHeight)
      canvas.width = window.devicePixelRatio * canvasWidth
      canvas.height = window.devicePixelRatio * canvasHeight
      cxt.scale(window.devicePixelRatio || 1, window.devicePixelRatio || 1)
      cxt.fillStyle = '#5f5f5f'
      cxt.strokeStyle = '#5f5f5f'
      cxt.lineWidth = 1
      cxt.font = '12px'
      cxt.textAlign = 'left'
      cxt.beginPath()
      for (let i = -1, l = Math.ceil(canvasWidth / pxInterval); i <= l; i++) {
        let x = add(mul(pxInterval, i), 0)
        let sec = add(mul(i, timeInterval), 0)
        cxt.fillStyle = '#ddd'
        cxt.font = '12px microsoft yahei'
        cxt.fillText(secToTime(sec, true), x + 2, 12)
        cxt.moveTo(x, 10)
        cxt.lineTo(x, 25)
        for (let j = 1; j < 10; j++) {
          cxt.moveTo(x + (j * pxInterval) / 10, j === 5 ? 15 : 18)
          cxt.lineTo(x + (j * pxInterval) / 10, 25)
        }
      }
      cxt.closePath()
      cxt.stroke()
    }
  }
}
const { width, height } = defineProps<{ width: number; height: number }>()
const instance = getCurrentInstance()
const scale = inject('scale') as Ref<number>
const pxPerSec = inject('pxPerSec') as Ref<number>
const updateCurrentTime = inject('updateCurrentTime') as (val: number) => void
const updateScale = inject('updateScale') as (val: number) => void
watchEffect(() => {
  if (instance) {
    const timeInterval = getTimeInterval(scale.value)
    const pxInterval = timeInterval * pxPerSec.value
    drawTimeline(instance.refs.canvas, timeInterval, pxInterval)
  }
})
onMounted(() => {
  if (instance) {
    const timeInterval = getTimeInterval(scale.value)
    const pxInterval = timeInterval * pxPerSec.value
    drawTimeline(instance.refs.canvas, timeInterval, pxInterval)
  }
})

const mousewheel = (e: WheelEvent) => {
  if (e.deltaY) {
    updateScale(between(scale.value, 1, 150))
  }
}
const mousedown = (e: MouseEvent) => {
  const x = e.offsetX
  updateCurrentTime(x / pxPerSec.value)
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="stylus">
@import '../../assets/varibles.styl'
</style>
